package com.daisuxia.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daisuxia.back.service.ILianLianService;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.web.common.reslult.Status;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BankAllInfo;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.pojo.UserCardInfo;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IUserBankService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.SendSmsUtil;

import redis.clients.jedis.JedisCluster;

@Controller
@RequestMapping(value = "/lianlianBindCard")
public class LianLianBindCardController extends BaseController {
    Logger logger = Logger.getLogger(getClass());
    
    public final static String SMS_SEND_COUNT_MAX = "SMS_SEND_COUNT_MAX";// 发送验证码每天限制条数
    public final static int INFECTIVE_SMS_DAY = 86400;// 短信次数有效期
    
    @Autowired
    private ILianLianService lianlianService;
    @Autowired
    private IUserService userService;
    @Autowired
    private JedisCluster jedisCluster;
    @Autowired
    private IUserBankService userBankService;
    @Autowired
    private IBorrowOrderService borrowOrderService;

    /**
     * 获取lianlian token
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "getLianLianToken")
    public void getLianLianToken(HttpServletRequest request, HttpServletResponse response, Model model) {
        String LIANLIAN_TOKEN_TOKEN = "LIANLIAN_TOKEN_TOKEN_"; // 生成手机认证码频繁标识key
        String telephone = request.getParameter("mobilePhone");
        Map<String, Object> retMap = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        User logUser = null;
        try {
           logUser = this.loginFrontUserByDeiceId(request);

            if (null == logUser) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            logger.error("getLianLianToken userId=" + logUser.getId() + " user is not null");
            Long remainTime = checkForFront(LIANLIAN_TOKEN_TOKEN, telephone, 60);
            
            if (remainTime > 0) {
                code = Status.FREQUENT.getName();
                retMap.put("time", remainTime);
                return;
            }
            logger.error("getLianLianToken userId=" + logUser.getId() + " remainTime success " + remainTime);
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            if (null == user) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            logger.error("getLianLianToken userId=" + logUser.getId() + " user is not null userPhone=" + user.getUserPhone());
            Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(logUser.getId()));
            if (1 == checkResult) {
                msg = "您有借款申请正在审核或未还款完成，暂不能修改银行卡。";
                return;
            }
            logger.error("getLianLianToken userId=" + logUser.getId() + " checkResult=" + checkResult);
            if ((StringUtils.isBlank(user.getRealname())) || (!"1".equals(user.getRealnameStatus()))) {
                msg = "请填写个人信息";
                return;
            }
            logger.error("getLianLianToken userId=" + logUser.getId() + " 个人信息验证通过");

            Map<String, String> pams = this.getParameters(request);
            String phone = pams.get("phone") == null ? "" : pams.get("phone");
            String bankId = pams.get("bank_id") == null ? "" : pams.get("bank_id");
            String cardNo = pams.get("card_no") == null ? "" : pams.get("card_no");
            logger.error("getLianLianToken userId="+logUser.getId()+",actName:"+user.getRealname()+",phone:"+phone+",idNo:"+user.getIdNumber()+
            		",cardNo:"+cardNo+",bankId:"+bankId);
            Map<String, String> bankAllInfo = userBankService.selectBankByPrimaryKey(Integer.parseInt(bankId));
            if (StringUtils.isBlank(phone)) {
                msg = "预留手机号码不能为空";
                return;
            }
            if (StringUtils.isBlank(bankId)) {
                msg = "银行不能为空";
                return;
            }
            if (StringUtils.isBlank(cardNo)) {
                msg = "银行卡号不能为空";
                return;
            }
            if(null != bankAllInfo && BankAllInfo.BANK_STATUS_NO.equals(bankAllInfo.get("bankStatus"))){
                msg = "暂时不支持" + bankAllInfo.get("bankName") + "的绑定更换业务";
                return;
            }
            if (!phone.trim().equals(user.getUserPhone())) {
            	msg = "当前登录手机号码与银行卡预留手机号码不符";
                return;
			}
            Map<String, String> tokenParaMap = new HashMap<String, String>();
            tokenParaMap.put("phone", phone.trim());
            tokenParaMap.put("bankCode", String.valueOf(bankAllInfo.get("bankCode")));
            tokenParaMap.put("cardNo", cardNo.trim());
            tokenParaMap.put("userId", user.getId());
            tokenParaMap.put("actName", user.getRealname());//user.getRealname()"刘伟"
            tokenParaMap.put("idNo", user.getIdNumber());//user.getIdNumber()"430703199303096213"

            //请求金运通
            Map<String, Object> tokenRetMap = lianlianService.getBindCardToken2(tokenParaMap);
            
            if ("S0000000".equals(tokenRetMap.get("code"))) {
            	String rand = String.valueOf(Math.random()).substring(2).substring(0, 6);// 6位固定长度
            	String smsCountRegister = SMS_SEND_COUNT_MAX + phone;
				Integer smsCount=0;
				if(jedisCluster.get(smsCountRegister)!=null){
					smsCount = Integer.valueOf(jedisCluster.get(smsCountRegister));
				}
				Map<String, String> intervalMap = SysCacheUtils.getConfigMap(BackConfigParams.INTERVAL);
				int SMS_SEND_COUNT_MAX = Integer.valueOf(intervalMap.get("INTERVAL_SMS_COUNT"));
				if(smsCount<=SMS_SEND_COUNT_MAX){
					if (SendSmsUtil.sendBindCardSmsCL(phone, rand)) {
						if(smsCount==0){
							jedisCluster.setex(smsCountRegister,INFECTIVE_SMS_DAY, String.valueOf(smsCount+1));
						}
						//存入redis
						jedisCluster.setex("XJX_TOKEN_USERID_CODE"+user.getId(), 600, rand);
						jedisCluster.set("XJX_TOKEN_USERID" + user.getId(), String.valueOf(tokenRetMap.get("bindCardId")));
						jedisCluster.expire("XJX_TOKEN_USERID" + user.getId(), 1500);
						code = "0";
						msg = "成功获取验证码";      //cardSmsCode_18516777211_      cardSmsCode_18519777211_
					}else {
						code = "-1";
						msg = "短信发送失败";
					}
				}else{
					msg = "24小时内您的验证码发送次数已经超过上线";
				}
			}else if ("ER001001".equals(tokenRetMap.get("code"))) {
				code = String.valueOf(tokenRetMap.get("code"));
				msg = "该银行卡并不支持";
			}else {
				code = String.valueOf(tokenRetMap.get("code"));
				msg = String.valueOf(tokenRetMap.get("msg"));
			}
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("getLianLianToken userId=" + (null != logUser ? logUser.getId() : "") + " error", e);
        } finally {
            retMap.put("code", code);
            retMap.put("message", msg);
            logger.error("getLianLianToken userId=" + (null != logUser ? logUser.getId() : "") + " message=" + msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(retMap));
        }
    }

    /**
     * 重新绑卡时，校验是否有借款订单
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "validBorrowOrder")
    public void validBorrowOrder(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map<String, Object> retMap = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        User logUser = null;
        try {
            logUser = this.loginFrontUserByDeiceId(request);
            if (null == logUser) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            logger.error("validBorrowOrder userId=" + logUser.getId() + " user is not null");
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            if (null == user) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            logger.error("validBorrowOrder userId=" + logUser.getId() + " user is not null userPhone=" + user.getUserPhone());
            Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(logUser.getId()));
            if (1 == checkResult) {
                msg = "您有借款申请正在审核或未还款完成，暂不能修改银行卡。";
                return;
            }
            logger.error("validBorrowOrder userId=" + logUser.getId() + " checkResult=" + checkResult);

            code = Status.SUCCESS.getName();
            msg = Status.SUCCESS.getValue();
        } catch (Exception e) {
            logger.error("validBorrowOrder userId=" + (null != logUser ? logUser.getId() : "") + " error", e);
        } finally {
            retMap.put("code", code);
            retMap.put("message", msg);
            logger.error("validBorrowOrder userId=" + (null != logUser ? logUser.getId() : "") + " message=" + msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(retMap));
        }
    }

    
    /**
     * lianlian token 验证
     *
     * @param request
     * @param response
     * @param model
     */
    @RequestMapping(value = "tokenValidate")
    public void tokenValidate(HttpServletRequest request, HttpServletResponse response, Model model) {
        String LIANLIAN_TO_TOKEN_VALIDATE = "LIANLIAN_TO_TOKEN_VALIDATE_"; // 生成手机认证码频繁标识key
        String telephone = request.getParameter("mobilePhone");
        Map<String, Object> retMap = new HashMap<String, Object>();
        String code = Status.FAILD.getName();
        String msg = "绑定失败";
        User logUser = null;
        try {

            logUser = this.loginFrontUserByDeiceId(request);
            if (null == logUser) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            logger.error("tokenValidate userId=" + logUser.getId() + " user is not null");
            Long remainTime = checkForFront(LIANLIAN_TO_TOKEN_VALIDATE, telephone);
            if (remainTime > 0) {
                code = Status.FREQUENT.getName();
                retMap.put("time", remainTime);
                msg = Status.FREQUENT.getValue();
                return;
            }
            logger.error("tokenValidate userId=" + logUser.getId() + " remainTime success " + remainTime);
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            if (null == user) {
                code = Status.LOGIN.getName();
                msg = Status.LOGIN.getValue();
                return;
            }
            logger.error("tokenValidate userId=" + logUser.getId() + " user is not null userPhone=" + user.getUserPhone());
            Integer checkResult = borrowOrderService.checkBorrow(Integer.parseInt(logUser.getId()));
            if (1 == checkResult) {
                msg = "您有借款申请正在审核或未还款完成，暂不能修改银行卡。";
                return;
            }
            logger.error("tokenValidate userId=" + logUser.getId() + " checkResult=" + checkResult);
            if ((StringUtils.isBlank(user.getRealname())) || (!"1".equals(user.getRealnameStatus()))) {
                msg = "请填写个人信息";
                return;
            }
            logger.error("tokenValidate userId=" + logUser.getId() + " 个人信息验证通过");

            Map<String, String> pams = this.getParameters(request);

            String bindCardId = jedisCluster.get("XJX_TOKEN_USERID" + user.getId());

            String verifyCode = pams.get("verify_code") == null ? "" : pams.get("verify_code");
            String phone = pams.get("phone") == null ? "" : pams.get("phone");
            String bankId = pams.get("bank_id") == null ? "" : pams.get("bank_id");
            String cardNo = pams.get("card_no") == null ? "" : pams.get("card_no");
            logger.error("tokenValidate userId=" + logUser.getId() + " bindCardId:" + bindCardId + ",verifyCode:" + verifyCode);


            if (StringUtils.isBlank(bindCardId)) {
                msg = "验证信息已过期，请稍后再试";
                return;
            }
            if (StringUtils.isBlank(phone)) {
                msg = "预留手机号码不能为空";
                return;
            }
            if (StringUtils.isBlank(bankId)) {
                msg = "银行不能为空";
                return;
            }
            if (StringUtils.isBlank(cardNo)) {
                msg = "银行卡号不能为空";
                return;
            }
            if (StringUtils.isBlank(verifyCode)) {
                msg = "短信验证码不能为空";
                return;
            }
            if (!phone.trim().equals(user.getUserPhone())) {
            	msg = "当前登录手机号码与银行卡预留手机号码不符";
                return;
			}
            
            //验证短信验证码
            //Map<String, Object> resultMap = JYTUtils.JYTauthCode(verifyCode, phone, bindCardId, logUser.getId(),logger);
            if (verifyCode.equals(jedisCluster.get("XJX_TOKEN_USERID_CODE"+user.getId()))){
            	code = "0000";
				msg = "绑卡成功";
				
				Map<String, String> tokenParaMap = new HashMap<String, String>();
	            tokenParaMap.put("userId", user.getId());
	            tokenParaMap.put("bankId", bankId.trim());
	            tokenParaMap.put("cardNo", cardNo.trim());
	            tokenParaMap.put("phone", phone.trim());
	            tokenParaMap.put("realName", user.getRealname());
	            tokenParaMap.put("no_agree", "默认签约号无");
	            
	            lianlianService.bindCard(code, tokenParaMap);
            }else {
            	code = "-1";
				msg = "验证码错误";
            }
            /*

            Map<String, Object> tokenRetMap = lianlianService.bindCardValidate(tokenParaMap);

            code = String.valueOf(tokenRetMap.get("code"));
            msg = String.valueOf(tokenRetMap.get("msg"));*/

        } catch (Exception e) {
            logger.error("tokenValidate userId=" + (null != logUser ? logUser.getId() : "") + " error", e);
        } finally {
            retMap.put("code", code);
            retMap.put("message", msg);
            logger.error("tokenValidate userId=" + (null != logUser ? logUser.getId() : "") + " message=" + msg);
            JSONUtil.toObjectJson(response, JSONUtil.beanToJson(retMap));
        }
    }


    /**
     * 第一次绑定银行卡页面
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("credit-card/firstUserBank")
    public String firstUserBank(HttpServletRequest request, HttpServletResponse response, Model model) {
    	
        User logUser = this.loginFrontUserByDeiceId(request);
        List<Map<String, Object>> mapList = userBankService.findAllBankInfo();//查询所有的银行
        model.addAttribute("bankList", mapList);
        if (logUser != null) {
            UserCardInfo info = userService.findUserBankCard(Integer.parseInt(logUser.getId()));//查找用户的有效银行账号
            User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
            model.addAttribute("realName", user.getRealname());//真实姓名
            model.addAttribute("deviceId", request.getParameter("deviceId"));
            model.addAttribute("mobilePhone", request.getParameter("mobilePhone"));
            if (null == info) {
                model.addAttribute("bankName", "请选择银行");
                return "userinfo/firstUserBank"; //到添加银行卡页面
            } else {
                model.addAttribute("cardId", info.getId());
                model.addAttribute("bankId", info.getBank_id());
                model.addAttribute("bankName", info.getBankName());
                model.addAttribute("bankCard", info.getCard_no());
                model.addAttribute("userPhone", info.getPhone());
                model.addAttribute("openName", info.getOpenName());//银行开户姓名
            }
        } else {
            model.addAttribute("msg", "登录已失效,请重新登录");
        }
        
        return "userinfo/showUserBank";//到展示银行卡页面
    }
    
    /**
     * 重新绑定银行卡
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("credit-card/updateUserBank")
    public String updateUserBank(HttpServletRequest request, HttpServletResponse response, Model model) {
    	String deviceId = request.getParameter("deviceId");
		String mobilePhone = request.getParameter("mobilePhone");
		User logUser = this.loginFrontUserByDeiceId(request);
         List<Map<String, Object>> mapList = userBankService.findAllBankInfo();//查询所有的银行
         if (logUser != null) {
             User user = userService.searchByUserid(Integer.parseInt(logUser.getId()));
             model.addAttribute("bankList", mapList);
             model.addAttribute("bankName", "请选择银行");
             model.addAttribute("realName", user.getRealname());//真实姓名
             model.addAttribute("mobilePhone", mobilePhone);
     		 model.addAttribute("deviceId", deviceId);
         }
    	return "userinfo/firstUserBank";
    }

}
